package com.ittx.dzt.tiktok.service;

import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import open.dto.PackageDS;
import open.dto.PackageDetailDS;
import open.dto.ShipmentDispatchDto;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.json.JacksonTool;
import com.ittx.dzt.tiktok.constant.TiktokApiConstant;
import com.ittx.dzt.tiktok.handler.AbstractBaseTiktokApiHandler;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 确认拆单
 * <p>
 * cy.tiktok.order.split.confirm
 * /fulfillment/202309/orders/{order_id}/split (确认拆单，非欧美地区拆单调用) https://partner.tiktokshop.com/docv2/page/650aa8890fcef602bf329fcc?external_id=650aa8890fcef602bf329fcc
 * </p>
 *
 * @author gywang
 * @since 2024-07-25
 */
@Slf4j
@Service
public class TiktokOrderSplitConfirmService extends AbstractBaseTiktokApiHandler<ShipmentDispatchDto> {
    @Override
    public String getTiktokMethod() {
        return TiktokApiConstant.ORDER_SPLIT_CONFIRM;
    }

    @Override
    public String getLocalApiMethod() {
        return PlatformApiConstant.InboundInterface.TIKTOK_ORDER_SPLIT_CONFIRM;
    }

    @Override
    public Result doProcess(PlatformApiParamDTO platformApiParamDTO, ShipmentDispatchDto shipmentDispatchDTO) {
        Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
        if (validResult.hasError()) {
            return validResult;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("shop_cipher", getShopCipher(platformApiParamDTO));
        String url = getDefaultUrl(platformApiParamDTO.getStoreConfig());
        url = StringUtils.replace(url, "{order_id}", shipmentDispatchDTO.getSourceOrderCode());
        Map<String, Object> reqBody = new HashMap<>();
        List<Map<String, Object>> packList = new ArrayList<>();
        reqBody.put("splittable_groups", packList);

        for (PackageDS pack : shipmentDispatchDTO.getPacks()) {
            Map<String, Object> tkPack = new HashMap<>();
            packList.add(tkPack);
            tkPack.put("id", pack.getContainerId().toString());
            List<String> lines = new ArrayList<>();
            for (PackageDetailDS d : pack.getDetails()) {
                lines.add(d.getSourceLineNum());
            }
            tkPack.put("order_line_item_ids", lines);
        }

        return this.executeTiktokApi(url, platformApiParamDTO.getStoreConfig(), params, JacksonTool.toJson(reqBody), platformApiParamDTO.getRequestId(), TiktokApiConstant.ApiHttpMethod.POST);
    }
}
